<?php	ob_start();
  #-------------------------------------------------------------------------------
  # Tracking code for click

  # Pgmmr        : RR
  # Date Created :   21-1-2004
  # Date Modfd   :   16-1-2005
  # Last Modified: By DPT on June/01/05 (if click is in IP block period, record the click and forward click to URL, but merchant need not pay)
  #				   By DPT on July/30/05 (to incorporate sub-id tracking)	
  #				   By DPT on August/01/05 (to incorporate flatrate/percentage for commission)
  #				   By DPT on September/07/05 (to change the ipaddress getting line)
  #-------------------------------------------------------------------------------

    include_once 'includes/session.php';
    include_once 'includes/constants.php';
    include_once 'includes/functions.php';
    include_once 'testmail.php';

    $partners = new partners;
    $partners->connection($host,$user,$pass,$db);
	
	//if admin has set up the click rate in percentage
	//if($admin_clickrate_type=="percentage") $admin_clickrate 

    $Act                    =	trim($_GET['Act']);
    $aid					=	trim($_GET['aid']);                   //joinprogram id
    $linkid					=	trim($_GET['linkid']);                //ad link id
    $ipaddress				=   $HTTP_SERVER_VARS['REMOTE_ADDR'];     //getting ip address
	if(empty($ipaddress)) $ipaddress = $_SERVER['REMOTE_ADDR'];
    $link   			    =	substr($linkid,0,1);                  // getting type of ad(banner,text etc)
    $id     			    =	substr($linkid,1,strlen($linkid)-1);
    $status				    =	"";                                   // ad link status

    $referer 				= 	getenv(HTTP_REFERER);

	//get sub id
	$subid					= $_GET['subid'];
	$presenttime  			=   date("Y-m-d  H:i:s");
#------------------------------------------------------------------------
# getting redirecting url
# getting ad status
#------------------------------------------------------------------------
 switch($link) //
      {
        case 'H':    //link is  Html

                $sql        = "select * from partners_html where html_id=$id";
                $result     = @mysql_query($sql);
                $row        = @mysql_fetch_object($result) ;

                if(@mysql_num_rows($result)>0) {
                 $status    = $row->html_status; //linkid exist under given pgm
                 $url       = $row->html_url;
                 $pgmid     = $row->html_programid;
                }
                break;

        case 'T':   //link is  text

                $sql        = "select * from partners_text where text_id=$id";
                $result     = @mysql_query($sql);
                $row        = @mysql_fetch_object($result) ;

                if(@mysql_num_rows($result)>0){
                 $status    = $row->text_status;  //linkid exist under given pgm
                 $url       = $row->text_url;
                 $pgmid     = $row->text_programid;
                }
                break;

        case 'B':  //link is  banner

                $sql        ="select * from partners_banner where banner_id=$id";
                $result     = @mysql_query($sql);
                $row        = @mysql_fetch_object($result);
                 if(mysql_num_rows($result)>0)
                {
                 $status    =$row->banner_status;   //linkid exist under given pgm
                 $url       =$row->banner_url;
                 $pgmid     =$row->banner_programid;
                }
                break;

         case 'P':   //link is  popup

                $sql        ="select * from partners_popup where popup_id=$id";
                $result     = @mysql_query($sql);
                $row        = @mysql_fetch_object($result);
                 if(@mysql_num_rows($result)>0)
                {
                 $status    =$row->popup_status; //linkid exist under given pgm
                 $url       =$row->popup_url;
                 $pgmid     =$row->popup_programid;
                }
                break;

         case 'F':   //link is  flash

                $sql        ="select * from partners_flash where flash_id=$id";
                $result     = @mysql_query($sql);
                $row        = @mysql_fetch_object($result);
                 if(@mysql_num_rows($result)>0)
                {
                 $status    =$row->flash_status; //linkid exist under given pgm
                 $url       =$row->flash_swf;
                 $pgmid     =$row->flash_programid;
                }
                break;

           case 'R':   //link is PRODUCT

                $sql        ="select * from partners_product where prd_id=$id";
                $result     = @mysql_query($sql);
                $row        = @mysql_fetch_object($result);
                if(@mysql_num_rows($result)>0)
                {
                  $status    =$row->prd_status; //linkid exist under given pgm

                 if($type==1) {

                 	$url       = trim($row->prd_image);
                    $url       = trim($row->prd_image,'"');

                    }
                 else		    {
                 	$url       = trim($row->prd_url);
                    $url       = trim($row->prd_url,'"');
                    }

                 $pgmid     =$row->prd_programid;
                }
                break;

      }
	  
//Modified by SMA to validate the url
        # if the 1st part of the URL not contain http:/
        $url_test = substr($url, 0, 7);
        if($url_test!="http://")
        {
            $url   =    "http://".$url;
        }
//End modify
 
#------------------------------------------------------------------------
# getting redirecting url  ends here
#-----------------------------------------------------------------


#------------------------------------------------------------------------
# Checking whether the request comes from rotator
# gets joinid, join status and merchant id
#------------------------------------------------------------------------

# requests is from rotator
	if($Act=="Rotator") {

              #getting the joinid and merchant id
              $sql	=	"select * from partners_joinpgm where joinpgm_affiliateid=$aid and joinpgm_programid=$pgmid";
    	      $ret	=	@mysql_query($sql);
              if(@mysql_num_rows($ret)>0) {
                         $row		=	@mysql_fetch_object($ret);
                         $joinid	=	$row->joinpgm_id;
                         $mid		=	$row->joinpgm_merchantid;
              }

              # getting the rotaor status
              $sql	=	"select rotatorsta_status,(rotator_id) from partners_rotatorsta,partners_rotator where rotatorsta_merid=$mid and rotator_affilid=$aid and rotator_id=rotatorsta_roid";
              $ret	=	@mysql_query($sql);
   			  if(@mysql_num_rows($ret)>0)  {
          	   		   $row			=	@mysql_fetch_object($ret);
	                   $joinstatus	=	trim($row->rotatorsta_status);

    		 }
    }else{
    		# getting join status, merchantid, joinid
            $sql	=	"select * from partners_joinpgm where joinpgm_affiliateid=$aid and joinpgm_programid=$pgmid";
            $ret	=	@mysql_query($sql);
         	if(@mysql_num_rows($ret)>0) {
                $row		=	@mysql_fetch_object($ret);
                $joinstatus	=	trim($row->joinpgm_status);
                $joinid		=	$row->joinpgm_id;
                $mid		=	$row->joinpgm_merchantid;
           }
    }



#------------------------------------------------------------------------------
# getting affiliate status
#------------------------------------------------------------------------------
    $sql	=	"select * from partners_affiliate where affiliate_id=$aid";
    $ret	=	@mysql_query($sql);
    if(@mysql_num_rows($ret)>0){
             $row		=	@mysql_fetch_object($ret);
             $affstatus =	trim($row->affiliate_status);
    }


#------------------------------------------------------------------------------
# getting mercahnt status
#------------------------------------------------------------------------------
    $sql	=	"select * from partners_merchant where merchant_id=$mid";
    $ret	=	@mysql_query($sql);
    if(@mysql_num_rows($ret)>0) {
             $row		= @mysql_fetch_object($ret);
             $merstatus = trim($row->merchant_status);
             $randNo	= trim($row->merchant_randNo);

    }

#------------------------------------------------------------------------------
# getting program status
#------------------------------------------------------------------------------
    $sql="select * from partners_program where program_id=$pgmid";
    $ret=@mysql_query($sql);
    if(@mysql_num_rows($ret)>0)
    {
             $row			=	@mysql_fetch_object($ret);
             $pgmstatus		=	trim($row->program_status);
             $ipblocking	=	$row->program_ipblocking;

            list($cookieTime,$cookiePeriod)		=   explode(" ",trim($row->program_cookie));
    }

#----------------------------------------------------------------------------
# Adding raw clicks
#----------------------------------------------------------------------------

    $today  	   	=   date("Y-m-d");
#----------------------------------------------------------------------------
# Adding/updating raw click count  into partners_rawtrans_daily added on 17-JUNE-2006
#----------------------------------------------------------------------------

   InsertRawTrans_daily($pgmid, $aid,$mid, $linkid, $today);


#------------------------------------------------------------------------------
# Checking whether all the status are approved
#------------------------------------------------------------------------------
  //echo $affstatus.$merstatus.$joinstatus.$pgmstatus.strtolower($status);

  if(($affstatus=='approved') and ($merstatus=='approved') and ($joinstatus=='approved') and ($pgmstatus=='active') and (strtolower($status)=='active'))
  {

       # getting current time
        $currenttime  =   date("Y-m-d  H:i:s");
        $currenttime1 =   date("d-m-Y  H:i:s");

      //////////////////////////////////////////////////////////////////////////
      ///////// Cookie Tracking	////////////////////////////////////////////////
      //////////////////////////////////////////////////////////////////////////

      if($cookieTime==0) $cookieTime = "";

      # if mercahnt has set cookie
       if(!empty($cookieTime)) {

            /////////////////////// getting cookie values ///////////////////

            # get cookie value
            $TRACKCOOKIE_VALUE	= $_COOKIE["USERCOOKIE_FOR_TRACKING"];

            # get cookie value
	    	if (empty($TRACKCOOKIE_VALUE))
                $TRACKCOOKIE_VALUE = $HTTP_COOKIE_VARS["USERCOOKIE_FOR_TRACKING"];

           ////////////////////// getting cookie values///////////////////////



           # get all the avialabe pgms cookie
           $pgmCookies = explode(",",$TRACKCOOKIE_VALUE);

           # get  c0okie expire time for each pgm
           for($cookieIndex=0;$cookieIndex<count($pgmCookies);$cookieIndex++){
             list($pgmList[$cookieIndex],$timeLimit[$cookieIndex]) = explode(":",$pgmCookies[$cookieIndex]);
           }

          # checking wether the cookie already set for pgm
          $currTime = mktime(date("h"),date("i"),date("s"),date("m"),date("d"),date("y"));



           if(in_array($pgmid,$pgmList)) {
             # index
             $pos 	   = array_search($pgmid,$pgmList);

             # cookie already exists
             if($timeLimit[$pos]>$currTime){
                //--------------Added By DPT on July/28/07----------
                # store the click as a transaction and direct the user to the url
                # merchant need not pay for this click

	            # getting click approval type
	            $sql1    =   "select pgmstatus_clickapproval from partners_pgmstatus where pgmstatus_programid=$pgmid";
	            $result  =   @mysql_query($sql1)or die($sql1."<br/>".mysql_error());
	            $row     =   @mysql_fetch_object($result);
	            $approval        =   $row->pgmstatus_clickapproval;

                // automatic approval
                if($approval=="automatic")  $approvalstatus="approved";
                else $approvalstatus = "pending";

                // add transaction
                $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_dateofpayment ,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_country,transaction_subid,transaction_transactiontime) values ($joinid,'click','$approvalstatus','$today',0,'$today','$linkid',0,'$referer','$ipaddress','$name','$subid','$presenttime') ";
		        @mysql_query($sql);

                // redirecting to given url
			    header("location:$url");
			    exit;
			    //--------------End of Addition By DPT---------------
                //header("Location:admin/error.htm");
            	//exit;
            }

           }else $pos = count($pgmCookies);


                  ////////// update cookie values /////////////////////////////

                  # set new time

                   # checking cookie time


                  switch ($cookiePeriod){

               	  		case 'minute':
                        	 $newCookieTime 	= mktime(date("h"),date("i")+$cookieTime,date("s"),date("m"),date("d"),date("y"));
                             break;

	                    case 'hour':
                           	 $newCookieTime 	= mktime(date("h")+$cookieTime,date("i"),date("s"),date("m"),date("d"),date("y"));
                              break;

	                    case 'day':
	                          $newCookieTime 	= mktime(date("h"),date("i"),date("s"),date("m"),date("d")+$cookieTime,date("y"));
	                          break;

	                    case 'year':
	                         $newCookieTime 	= mktime(date("h"),date("i"),date("s"),date("m"),date("d"),date("y")+$cookieTime);
	                          break;
                  }


                  $pgmCookies[$pos] = $pgmid.":".$newCookieTime;
                  $cookieValue 		= implode(",",$pgmCookies);

                 # update cookie value


               setcookie ("USERCOOKIE_FOR_TRACKING",$cookieValue,time()+3600);



                 ////////// update ends here     /////////////////////////////
        }

       //////////////////////////////////////////////////////////////////////////
       ///////// End Cookie Tracking  ///////////////////////////////////////////
       //////////////////////////////////////////////////////////////////////////



        # adding currenttime+ipblocking time
        $sql      =   "select DATE_ADD('$currenttime',INTERVAL $ipblocking MINUTE) d " ;
        $ret      =   @mysql_query($sql);

        # getting  currenttime+ipblocking
        $row      =   @mysql_fetch_object($ret);
        $iptime   =   $row->d;


       # getting last click time for checking ip is blocked for the time being
       $sql   =   "select *,date_format(ipblocking_time,'%H/%i/%s/%d/%m/%y') as d from partners_ipblocking  where ipblocking_ipaddress='$ipaddress' and ipblocking_programid=$pgmid " ;
       $ret   =   @mysql_query($sql);

       # ip is present in the database
       if(@mysql_num_rows($ret)>0) {
            $row      =   @mysql_fetch_object($ret);
            $ipblock  =   $row->d;
            $ipid     =   $row->ipblocking_id;

            # comparing last click and current click time
            if(CompareTime($ipblock)) {
	
                # click is wthin the ip block time
                //--------------Added By DPT on June/01/05----------
                # store the click as a transaction and direct the user to the url
                # merchant need not pay for this click

	            # getting click approval type
	            $sql1    =   "select pgmstatus_clickapproval from partners_pgmstatus where pgmstatus_programid=$pgmid";
	            $result  =   @mysql_query($sql1)or die($sql1."<br/>".mysql_error());
	            $row     =   @mysql_fetch_object($result);
	            $approval        =   $row->pgmstatus_clickapproval;

                // automatic approval
                if($approval=="automatic")  $approvalstatus="approved";
                else $approvalstatus = "pending";

                $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_dateofpayment ,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_country,transaction_subid,transaction_transactiontime) values ($joinid,'click','$approvalstatus','$today',0,'$today','$linkid',0,'$referer','$ipaddress','$name','$subid','$presenttime') ";
		        @mysql_query($sql);

                // redirecting to given url
			    header("location:$url");
			    exit;
			    //--------------End of Addition By DPT---------------

                //header("Location:admin/error.htm");
                //exit;
            }else{
                #
                # record entry
                $pgmstatus    =   GetTransaction($mid,$pgmid,$joinid,$aid,$linkid,$admin_clickrate,$minimum_amount,$subid, $fraudsettings_clickseconds, $fraudsettings_recentclick, $fraudsettings_clickaction) ;      // added a parameter by pramod
                $pgmstatus    =   explode("~",$pgmstatus);

                # updating last click time
                $sql  ="update partners_ipblocking set ipblocking_time='$iptime',ipblocking_affiliateid=$aid,ipblocking_merchantid=$mid,ipblocking_programid=$pgmid,ipblocking_joinpgmid=$joinid,ipblocking_linkid='$linkid',ipblocking_click='$pgmstatus[0]',ipblocking_lead='$pgmstatus[1]',ipblocking_sale='$pgmstatus[2]',ipblocking_saletype='$pgmstatus[3]',ipblocking_statusid='$pgmstatus[4]',ipblocking_randNo='$randNo'  where ipblocking_id=$ipid";
                @mysql_query($sql);

           }
      }
      # ip address is not present in database.........firsttime login
      else{

          # genuine click
          # record entry
          $pgmstatus  =   GetTransaction($mid,$pgmid,$joinid,$aid,$linkid,$admin_clickrate,$minimum_amount,$subid, $fraudsettings_clickseconds, $fraudsettings_recentclick, $fraudsettings_clickaction) ;       // added a parameter by pramod
          $pgmstatus  =   explode("~",$pgmstatus);

           # updating last click time
          $sql    =   "insert into partners_ipblocking(ipblocking_ipaddress,ipblocking_time,ipblocking_affiliateid,ipblocking_merchantid,ipblocking_programid,ipblocking_joinpgmid,ipblocking_linkid,ipblocking_click,ipblocking_sale,ipblocking_lead,ipblocking_saletype,ipblocking_statusid,ipblocking_randNo)values('$ipaddress','$iptime',$aid,$mid,$pgmid,$joinid,'$linkid',$pgmstatus[0],$pgmstatus[2],$pgmstatus[1],'$pgmstatus[3]',$pgmstatus[4],'$randNo') ";
          @mysql_query($sql);
      }

  	 # redirecting to given url
     header("location:$url");
     exit;
	}else{

       # not a genuine click
	   header("Location:admin/error.htm");
       exit;
    }
#------------------------------------------------------------------------------
# Checking whether all the status are approved  ends here
#------------------------------------------------------------------------------




# inserting value into transaction table
 function GetTransaction($mid,$pgmid,$joinid,$aid,$linkid,$admin_clickrate,$minimum_amount,$subid, $clickseconds, $recentclick, $clickaction)
 {
		$ipaddress				=   $HTTP_SERVER_VARS['REMOTE_ADDR'];     //getting ip address
		if(empty($ipaddress)) $ipaddress = $_SERVER['REMOTE_ADDR'];
		$presenttime  			=   date("Y-m-d  H:i:s");

        $referer = getenv('HTTP_REFERER');
        # getting firstlevel commission
        $sql1	=	"select * from partners_firstlevel where  firstlevel_programid=$pgmid";
        $ret1	=	@mysql_query($sql1);
        $rows	=	@mysql_fetch_object($ret1);

        $clickrate	=	$rows->firstlevel_clickrate;
        $salerate	=	$rows->firstlevel_leadrate;
        $leadrate	=	$rows->firstlevel_salerate;
        $saletype	=	$rows->firstlevel_saletype;


        #checking whether any group exist for this program
        $sql	=	"select * from partners_group where  group_programid=$pgmid";
        $ret	=	@mysql_query($sql);

        # group exists
        if(@mysql_num_rows($ret)>0) {
          	       $row				=	@mysql_fetch_object($ret);
	               $group			=	$row->group_id;
	               $clickgroup		=	$row->group_clickrate;
                   $salegroup		=	$row->group_leadrate;
                   $leadgroup		=	$row->group_salerate;
                   $saletypegroup	=	$row->group_saletype;

	               # checking whether member of any group
	               $sql1	=	"select * from partners_joinpgm where  joinpgm_id=$joinid and joinpgm_group=$group";
	               $ret1	=	@mysql_query($sql1);

	               if(@mysql_num_rows($ret1)>0) {
	                     $clickrate	=	$clickgroup;
                         $salerate	=	$salegroup;
                         $leadrate	=	$leadgroup;
                         $saletype	=	$saletypegroup;
	               }

       }
      # close   checking whether any group exist for this program

	 // if admin has set up the click rate in %, then calculate the same here
	 if($GLOBALS['admin_clickrate_type']=="percentage") $admin_clickrate = ($clickrate*$admin_clickrate)/100;	

     # getting click approval type

       $sql1	=	"select * from partners_pgmstatus where pgmstatus_programid=$pgmid";
       $result	=	@mysql_query($sql1)or die($sql1."<br/>".mysql_error());
       $row		=	@mysql_fetch_object($result);

       $approval		=	$row->pgmstatus_clickapproval;
       $statusid		=	$row->pgmstatus_id;
       $mailmerchant 	=	$row->pgmstatus_mailmerchant;
       $mailaffiliate 	=	$row->pgmstatus_mailaffiliate;

       if($approval=="automatic")  {

             $approvalstatus="approved";          // automatic approval

             # Added BY PRAMOD FOR UPDATE CURENT+transaction AMOUNT IN AFFIL ACCOUNT-----------------//


     		 #  get merchant account

	         $sql        = "SELECT *  FROM `merchant_pay`  WHERE pay_merchantid='$mid' ";
	         $res        = @mysql_query($sql);
             echo @mysql_error();

             $num		=	@mysql_num_rows($res);
             $cut_off   =	$minimum_amount;

             if($num>0){
	             $row1   			 =   @mysql_fetch_object($res);
                 $merchant_balance   = $row1->pay_amount;

                 if(($merchant_balance-($clickrate+$admin_clickrate) )<=$cut_off) {
                     header("Location:money_empty_error.php");
                      exit;
                 }
                 else{

					# Update Account info of admin,affil,merchant

					# Adding money to affiliate account
                    $merchant_balance = $merchant_balance-($clickrate+$admin_clickrate);

                    $sql1       = "SELECT *  FROM `affiliate_pay` where pay_affiliateid=$aid ";
                    $res1       = @mysql_query($sql1);
                    echo @mysql_error();

                    $num=@mysql_num_rows($res1);
                    if($num>0){
                        $row1   	=  @mysql_fetch_object($res1);
                        $curamount  =  $row1->pay_amount;
                        $curamount  =  $curamount + $clickrate;

                        $sql2 = "update affiliate_pay set pay_amount='$curamount' where pay_affiliateid=$aid";
                        $ret2 = @mysql_query($sql2);
                     }else{
                        $sql2 = "INSERT INTO  affiliate_pay set pay_affiliateid=$aid , pay_amount='$clickrate'";
                        $ret2 = @mysql_query($sql2);
                     }

    				# affiliate account editing Ends here

    				# Subtract Money From Merchant Account
                    $sql        = "UPDATE  `merchant_pay` SET  pay_amount=$merchant_balance  WHERE pay_merchantid='$mid' ";
                    $res        = @mysql_query($sql);
    				# END OF  Subtract Money From Merchant Account

    				# Adding To Admins Account
                    $sql1      = "SELECT *  FROM `admin_pay`  ";
                    $res1      = @mysql_query($sql1);
                    echo @mysql_error();

                    $num	=	@mysql_num_rows($res1);

                    if($num>0){
                       $row1   			   =  @mysql_fetch_object($res1);
                       $admin_curamount    = $row1->pay_amount;
                       $admin_curamount    = $admin_curamount+$admin_clickrate;
                    }

                    $sql  = "UPDATE `admin_pay` SET `pay_amount` = '$admin_curamount'";
                    $res  = @mysql_query($sql);

     			# END OF Adding to admin's account
                }
           }

     	   #	 END OF CODE  Added BY PRAMOD FOR UPDATE CURENT AMOUNT IN AFFIL,MERCHANT,ADMIN ACCOUNT

	       $today         = date("Y-m-d");
	       $admin_amount  = $admin_clickrate;

           /////////// getting country /////////////////////
             $ip 			= $GLOBALS['REMOTE_ADDR'];
             /* $ip_number = sprintf("%u", ip2long($ip));
         	  $sql       = "SELECT country_code2 name,country_name name1  FROM partners_countryFlag where  $ip_number >= ip_from  AND $ip_number <= ip_to ";
	          $ret       =mysql_query($sql);
	          if(mysql_num_rows($ret)) {
	                $row    =mysql_fetch_object($ret);
	                $name   =strtolower($row->name);
	                $name1  =($row->name1) ;
	          }
	          else{
	                $name="Unknown";
	                $name1="Unknown";
	         }*/
           /////////////////////////////////////////////////
		   
		   //--------Geo Targeting--------------
          //checking ip of user against offer available countries
	      $user_ip = (ip2long($ip) < 0 ? -1 * ip2long($ip) : ip2long($ip));
	      $temp_con = "OUT";

	      $selq = "SELECT `program_countries`,`program_geotargeting_click` FROM `partners_program` WHERE `program_id` = $pgmid";
	      $row  = mysql_fetch_object(mysql_query($selq));
	      $offer_in = explode(",",$row->program_countries);
		  
		  //if geo-targeting feature is enabled for click, then check whether the click is from allowed list of countries
		  if($row->program_geotargeting_click)
		  {
			  for($cind=0;$cind<count($offer_in);$cind++){
			  $selq = "SELECT `ip_from`,`ip_to` FROM `partners_countryFlag` WHERE `country_name` = '".$offer_in[$cind]."'"
					  ." AND ip_from <=".$user_ip." AND `ip_to` >=".$user_ip."";
					if(mysql_num_rows(mysql_query($selq))) $temp_con = "IN";
			  }
		   }
		   else $temp_con = "IN";

	      // add transaction
	      if($temp_con == "OUT")
	      	$sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_country,transaction_subid,transaction_transactiontime) values ($joinid,'click','$approvalstatus','$today',0,'$linkid',0,'$referer','$ipaddress','$name','$subid','$presenttime') ";
	      else
           	$sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_dateofpayment ,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_country,transaction_subid,transaction_transactiontime) values ($joinid,'click','$approvalstatus','$today',$clickrate,'$today','$linkid','$admin_amount','$referer','$ipaddress','$name','$subid','$presenttime') ";

	//Modified on 19-JUNE-2006 by SMA
		   if(CheckMultipleRepeatingClicks($joinid, $linkid, $today,$clickseconds, $recentclick, $clickaction))  {
			   @mysql_query($sql);
			}
			else
			{
				if($clickaction == "save as click") {
					@mysql_query($sql);
				}
			}
	//End Modified on 19-JUNE-2006			

	       $status=$clickrate."~".$salerate."~".$leadrate."~".$saletype."~".$statusid;

      }
      else  # manuall approval
      {
          $approvalstatus = "pending";
	      $today          = date("Y-m-d");
	      $admin_amount   = $admin_clickrate;
          /////////// getting country /////////////////////
              $ip 		 = $GLOBALS['REMOTE_ADDR'];
             /* $ip_number = sprintf("%u", ip2long($ip));
         	  $sql       = "SELECT country_code2 name,country_name name1  FROM partners_countryFlag where  $ip_number >= ip_from  AND $ip_number <= ip_to ";
	          $ret       = mysql_query($sql);
	          if(mysql_num_rows($ret)) {
	                $row    =mysql_fetch_object($ret);
	                $name   =strtolower($row->name);
	                $name1  =($row->name1) ;
	          }
	          else{
	                $name="Unknown";
	                $name1="Unknown";
	         } */
           /////////////////////////////////////////////////

          //checking ip of user against offer available countries
	      $user_ip = (ip2long($ip) < 0 ? -1 * ip2long($ip) : ip2long($ip));
	      $temp_con = "OUT";

	      $selq = "SELECT `program_countries`,`program_geotargeting_click` FROM `partners_program` WHERE `program_id` = $pgmid";
	      $row  = mysql_fetch_object(mysql_query($selq));
	      $offer_in = explode(",",$row->program_countries);

		  //if geo-targeting feature is enabled for click, then check whether the click is from allowed list of countries
		  if($row->program_geotargeting_click)
		  {
			  for($cind=0;$cind<count($offer_in);$cind++){
			  $selq = "SELECT `ip_from`,`ip_to` FROM `partners_countryFlag` WHERE `country_name` = '".$offer_in[$cind]."'"
					  ." AND ip_from <=".$user_ip." AND `ip_to` >=".$user_ip."";
					if(mysql_num_rows(mysql_query($selq))) $temp_con = "IN";
			  }
		   }
		   else $temp_con = "IN";

	      // add transaction
	      if($temp_con == "OUT")
	      	$sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_country,transaction_subid,transaction_transactiontime) values ($joinid,'click','$approvalstatus','$today',0,'$linkid',0,'$referer','$ipaddress','$name','$subid','$presenttime') ";
	      else
            $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_country,transaction_subid,transaction_transactiontime) values ($joinid,'click','$approvalstatus','$today',$clickrate,'$linkid','$admin_amount','$referer','$ipaddress','$name','$subid','$presenttime') ";

	//Modified on 19-JUNE-2006 by SMA
		  if(CheckMultipleRepeatingClicks($joinid, $linkid, $today,$clickseconds, $recentclick, $clickaction))
			   @mysql_query($sql);
		  else
			{
				if($clickaction == "save as click") {
					@mysql_query($sql);
				}
			}
	//Modified on 19-JUNE-2006	  

	      $status=$clickrate."~".$salerate."~".$leadrate."~".$saletype."~".$statusid;
     }

     if ($mailmerchant=="yes") {
         MailMerchant($aid,$mid,$pgmid,$clickrate,$admin_clickrate,"click");
     }

     if($mailaffiliate=="yes"){
         MailAffilaite($aid,$mid,$pgmid,$clickrate,"click");
     }

 return($status);
}
 # end function

 # comparing date (last login,current login)
function CompareTime($ipblock)
{
//comparing date
       $dtarray       =explode("/",$ipblock);
       $iphour        =$dtarray[0];
       $ipminute      =$dtarray[1];
       $ipsecond      =$dtarray[2];
       $ipdate        =$dtarray[3];
       $ipmonth       =$dtarray[4];
       $ipyear        =$dtarray[5];

 //current
       $d=date("d");
       $m=date("m");
       $y=date("Y");
       $h=date("H");
       $i=date("i");
       $s=date("s");
       $today=mktime($h,$i,$s,$m,$d,$y);
       $ipblock= mktime($iphour,$ipminute,$ipsecond,$ipmonth,$ipdate,$ipyear);

       if($ipblock>$today)
          return true;
       else
          return false;

}
# ends here



 //------------------------------------------------------------------------------------
    # This function is used to insert/update the  raw click count into
    # the table partners_rawtrans_daily
    #Created on 17-JUNE-2006
    //------------------------------------------------------------------------------------
    function InsertRawTrans_daily($programid, $aid,$mid, $linkid, $today)
    {
                $daily_click        = 1;
                $sql           = "SELECT * FROM partners_rawtrans_daily";
                $sql_where = "  WHERE  transdaily_affiliateid='$aid' AND transdaily_programid='$programid'
                              AND  transdaily_merchantid='$mid' AND transdaily_date ='$today'
                              AND transdaily_linkid = '$linkid'";
                            $res        = mysql_query($sql.$sql_where);
                if(mysql_num_rows($res)>0)
                {
                    #get the existing impression count
                    $row        = mysql_fetch_object($res);
                    $daily_click += $row->{transdaily_click};

                    #update
                    $sql         = "UPDATE partners_rawtrans_daily SET ";
                    $sql.= " transdaily_click = $daily_click ".$sql_where;

                }
                else
                {
                        #insert record
                    $sql = "INSERT INTO `partners_rawtrans_daily` SET
                            transdaily_affiliateid='$aid' , transdaily_programid='$programid',
                            transdaily_merchantid='$mid' , transdaily_date ='$today' ,
                            transdaily_linkid = '$linkid' , transdaily_click = $daily_click ";

                }

                $ret =@mysql_query($sql) ;
                return true;
    }// end function InsertRawTrans_daily
	
	
	//************************************************************************************	
	//  Created BY	: SMA
	//	Created On	: 19-JUNE-2006
	//  This function is used to check the fraud protection for recent clicks within the specified click seconds.
	//  The function directs to the aaction as specified by the admin in the fraud settings if the click is within the time specified.
	//************************************************************************************
	function CheckMultipleRepeatingClicks($joinid, $linkid, $today, $clickseconds, $recentclick, $clickaction)
	{
		if($recentclick == 1)
		{
			$ipaddress				=   $HTTP_SERVER_VARS['REMOTE_ADDR'];     //getting ip address
			if(empty($ipaddress)) $ipaddress = $_SERVER['REMOTE_ADDR'];
		
			$sql_click = "SELECT *,date_format(transaction_transactiontime,'%H/%i/%s/%d/%m/%y') as transtime FROM partners_transaction WHERE ".
			" transaction_joinpgmid = '$joinid' AND ".
			" transaction_type = 'click' AND ".
			" transaction_linkid = '$linkid' AND ".
			" transaction_ip = '$ipaddress' ORDER BY transaction_id DESC";
			
			
			$res_click = mysql_query($sql_click);
			if(mysql_num_rows($res_click) > 0)
			{
				$row_click = mysql_fetch_object($res_click);
				$lasttime = $row_click->transaction_transactiontime;
					
				# adding currenttime + clickseconds time
				$sql_delay      =   "select date_format(DATE_ADD('$lasttime',INTERVAL $clickseconds SECOND),'%H/%i/%s/%d/%m/%y') d " ;
				$ret_delay      =   @mysql_query($sql_delay);
				# getting  currenttime + clickseconds
				$row_delay     =   @mysql_fetch_object($ret_delay);
				$nextclicktime =   $row_delay->d;
	
				//die("time = " .$nextclicktime);
				if(CompareTime($nextclicktime))
				{ 
					 return false;
				} 
				else
				{
					return true;
				}
			}
			else
				return true;
		}
		else
			return true;
	}

?>